
from lin import db,route_meta,group_required,login_required
from lin.redprint import Redprint
from flask import jsonify
from lin.exception import NotFound,ParameterException,Success
from lin.log import Logger

from app.models.book import Book
from app.validators.forms import BookSearchForm,CreateOrUpdateBookForm
from app.libs.error_code import BookNotFound

book_api = Redprint('book')

#新增书籍
@book_api.route('/',methods=['POST'])
def create_book():
    form = CreateOrUpdateBookForm().validate_for_api()
    book = Book.query.filter_by(title=form.title.data).first()
    if book is not None:
        raise ParameterException(msg='图书已存在')
    with db.auto_commit():
        new_book = Book()
        new_book.title = form.title.data
        new_book.author = form.author.data
        new_book.summary = form.author.data
        new_book.image = form.image.data
        db.seesion.add(new_book)
    return Success(msg='增加图书成功')

#更新图书
@book_api.route('/<id>',methods=['PUT'])
def update_book():
    form = CreateOrUpdateBookForm().validate_for_api()
    book = Book.query.filter_by(id=id).first()
    if book is None:
        raise BookNotFound()
    with db.auto_commit():
        book.title = form.title.data
        book.author = form.author.data
        book.summary = form.summary.data
        book.image = form.image.data
    return Success(msg='更新图书成功')

#删除图书
@book_api.route('/<id>',methods=['DELETE'])
@route_meta('删除图书',module='图书')
@group_required
def delete_book(id):
    book: Book = Book.query.filter_by(id=id).first()
    if book is None:
        raise BookNotFound()
    book.delete(commit=True)
    return Success(msg='删除图书成功')

@book_api.route('/patch',methods=['DELETE'])
@route_meta('删除图书',module='图书')
@group_required
def delete_books():
    books = Book.query.filter_by().all()
    if books is None or len(books) < 1:
        raise BookNotFound()
    for book in books:
        book.delete(commit=True)
    return Success(msg='删除所有图书成功')


#获取所有图书
@book_api.route('/',methods=['GET'])
def get_books():
    books = Book.query.filter_by().all()
    if books is None or len(books) < 1:
        raise BookNotFound()
    return jsonify(books)

@book_api.route('/<id>',methods=['GET'])
@Logger(template='{user.nickname}用户查了一本书')
@login_required
def get_book(id):
    book = Book.query.filter_by(id=id).first()
    if book is None:
        raise NotFound(msg='没有找到相关书籍')
    return jsonify(book)

@book_api.route('/search',methods=['GET'])
def search():
    form = BookSearchForm().validate_for_api()
    q = '%'+form.q.data+'%'
    books = Book.query.filter(Book.title.like(q)).all()
    if books is None or len(books) < 1:
        raise BookNotFound()
    return jsonify(books)




